import { Table, Tag, Typography, Card, Button, Space, Modal, Form, Input, Select, InputNumber, DatePicker, message, Tabs, Row, Col } from '@/utils/antd-imports';
import { EditOutlined, PlusOutlined, CheckOutlined, CloseOutlined, SendOutlined, ClockCircleOutlined } from '@/utils/icons';
import React, { useState } from 'react';
import moment from 'moment';

const { Title, Text } = Typography;
const { Option } = Select;
const { TabPane } = Tabs;

// 模拟产值数据
const generateOutputValueData = () => {
  const data = [];
  const employeeTypes = ['公司自由人', '正式员工', '外协人员', '临时工'];
  const businessTypes = ['开发', '设计', '测试', '运维', '管理'];
  const projects = ['前端开发项目', '后端服务重构', '数据分析平台', '移动应用开发'];
  const departments = ['研发部', '设计部', '质量部', '产品部'];
  
  for (let i = 1; i <= 20; i++) {
    data.push({
      id: i,
      serialNumber: i,
      employeeId: `EMP${String(i).padStart(4, '0')}`,
      employeeName: `员工${i}`,
      employeeType: employeeTypes[Math.floor(Math.random() * employeeTypes.length)],
      projectName: projects[Math.floor(Math.random() * projects.length)],
      accountPeriod: '2024-09',
      projectCode: `PRJ${String(i).padStart(6, '0')}`,
      projectManager: `项目经理${i}`,
      department: departments[Math.floor(Math.random() * departments.length)],
      projectLocation: '北京',
      hireDate: moment().subtract(Math.floor(Math.random() * 1000), 'days').format('YYYY-MM-DD'),
      projectStartDate: moment().subtract(Math.floor(Math.random() * 100), 'days').format('YYYY-MM-DD'),
      projectEndDate: moment().add(Math.floor(Math.random() * 100), 'days').format('YYYY-MM-DD'),
      resignationDate: Math.random() > 0.8 ? moment().add(Math.floor(Math.random() * 30), 'days').format('YYYY-MM-DD') : null,
      businessType: businessTypes[Math.floor(Math.random() * businessTypes.length)],
      hasOrder: Math.random() > 0.5 ? '是' : '否',
      unitPrice: Math.floor(Math.random() * 500) + 100,
      workDuration: Math.floor(Math.random() * 200) + 50,
      workDurationType: ['时', '天', '月'][Math.floor(Math.random() * 3)],
      deduction: Math.floor(Math.random() * 50),
      monthlyOutput: Math.floor(Math.random() * 10000) + 5000,
      monthlyOutputExcludingTax: Math.floor(Math.random() * 8500) + 4250,
      status: Math.random() > 0.5 ? 'pending' : 'submitted',
      createTime: moment().subtract(Math.floor(Math.random() * 30), 'days').format('YYYY-MM-DD HH:mm:ss'),
      submitTime: Math.random() > 0.5 ? moment().subtract(Math.floor(Math.random() * 10), 'days').format('YYYY-MM-DD HH:mm:ss') : null
    });
  }
  
  return data;
};

const OutputValueManagement = () => {
  const [activeTab, setActiveTab] = useState('pending');
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState(null);
  const [form] = Form.useForm();
  
  const outputValueData = generateOutputValueData();
  const pendingData = outputValueData.filter(item => item.status === 'pending');
  const submittedData = outputValueData.filter(item => item.status === 'submitted');

  // 处理编辑
  const handleEdit = (record) => {
    setCurrentRecord(record);
    form.setFieldsValue({
      ...record,
      hireDate: record.hireDate ? moment(record.hireDate) : null,
      projectStartDate: record.projectStartDate ? moment(record.projectStartDate) : null,
      projectEndDate: record.projectEndDate ? moment(record.projectEndDate) : null,
      resignationDate: record.resignationDate ? moment(record.resignationDate) : null
    });
    setEditModalVisible(true);
  };

  // 提交编辑
  const handleEditSubmit = () => {
    form.validateFields().then(values => {
      console.log('编辑产值数据:', values);
      message.success('产值数据更新成功');
      setEditModalVisible(false);
      form.resetFields();
    });
  };

  // 产值上报
  const handleSubmit = (record) => {
    Modal.confirm({
      title: '确认提交',
      content: '确定要提交该产值记录吗？',
      onOk() {
        console.log('提交产值记录:', record);
        message.success('产值记录提交成功');
      }
    });
  };

  // 批量产值上报
  const handleBatchSubmit = () => {
    const selectedData = activeTab === 'pending' ? pendingData : submittedData;
    Modal.confirm({
      title: '批量提交',
      content: `确定要批量提交 ${selectedData.length} 条产值记录吗？`,
      onOk() {
        console.log('批量提交产值记录:', selectedData);
        message.success(`成功提交 ${selectedData.length} 条产值记录`);
      }
    });
  };

  // 产值表格列定义
  const outputValueColumns = [
    {
      title: '序号',
      dataIndex: 'serialNumber',
      key: 'serialNumber',
      width: 80,
      fixed: 'left'
    },
    {
      title: '工号',
      dataIndex: 'employeeId',
      key: 'employeeId',
      width: 100,
      fixed: 'left'
    },
    {
      title: '姓名',
      dataIndex: 'employeeName',
      key: 'employeeName',
      width: 100,
      fixed: 'left'
    },
    {
      title: '员工类型',
      dataIndex: 'employeeType',
      key: 'employeeType',
      width: 120,
      render: (type) => {
        const colors = {
          '公司自由人': 'blue',
          '正式员工': 'green',
          '外协人员': 'orange',
          '临时工': 'red'
        };
        return <Tag color={colors[type]}>{type}</Tag>;
      }
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      key: 'projectName',
      width: 150
    },
    {
      title: '账期',
      dataIndex: 'accountPeriod',
      key: 'accountPeriod',
      width: 100
    },
    {
      title: '项目编号',
      dataIndex: 'projectCode',
      key: 'projectCode',
      width: 120
    },
    {
      title: '项目经理',
      dataIndex: 'projectManager',
      key: 'projectManager',
      width: 120
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
      width: 100
    },
    {
      title: '项目地',
      dataIndex: 'projectLocation',
      key: 'projectLocation',
      width: 100
    },
    {
      title: '入职时间',
      dataIndex: 'hireDate',
      key: 'hireDate',
      width: 120
    },
    {
      title: '入项时间',
      dataIndex: 'projectStartDate',
      key: 'projectStartDate',
      width: 120
    },
    {
      title: '离项时间',
      dataIndex: 'projectEndDate',
      key: 'projectEndDate',
      width: 120
    },
    {
      title: '离职时间',
      dataIndex: 'resignationDate',
      key: 'resignationDate',
      width: 120,
      render: (text) => text || '-'
    },
    {
      title: '业务类型',
      dataIndex: 'businessType',
      key: 'businessType',
      width: 100
    },
    {
      title: '是否有订单',
      dataIndex: 'hasOrder',
      key: 'hasOrder',
      width: 120,
      render: (text) => (
        <Tag color={text === '是' ? 'green' : 'red'}>
          {text}
        </Tag>
      )
    },
    {
      title: '单价（含税）',
      dataIndex: 'unitPrice',
      key: 'unitPrice',
      width: 120,
      render: (text) => `¥${text}`
    },
    {
      title: '工作时长',
      dataIndex: 'workDuration',
      key: 'workDuration',
      width: 120,
      render: (text, record) => `${text}${record.workDurationType}`
    },
    {
      title: '扣减',
      dataIndex: 'deduction',
      key: 'deduction',
      width: 100,
      render: (text) => `¥${text}`
    },
    {
      title: '当月产值',
      dataIndex: 'monthlyOutput',
      key: 'monthlyOutput',
      width: 120,
      render: (text) => `¥${text.toLocaleString()}`
    },
    {
      title: '当月产值（不含税）',
      dataIndex: 'monthlyOutputExcludingTax',
      key: 'monthlyOutputExcludingTax',
      width: 150,
      render: (text) => `¥${text.toLocaleString()}`
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          {activeTab === 'pending' && (
            <Button 
              type="link" 
              icon={<SendOutlined />} 
              onClick={() => handleSubmit(record)}
            >
              上报
            </Button>
          )}
        </Space>
      )
    }
  ];

  return (
    <div>
      <Card
        title="产值管理"
        extra={
          <Space>
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
            >
              新增产值
            </Button>
            {activeTab === 'pending' && (
              <Button 
                type="primary" 
                icon={<SendOutlined />}
                onClick={handleBatchSubmit}
              >
                批量上报
              </Button>
            )}
          </Space>
        }
      >
        <Tabs 
          activeKey={activeTab} 
          onChange={setActiveTab}
          type="card"
        >
          <TabPane 
            tab={
              <span>
                <ClockCircleOutlined />
                待提交 ({pendingData.length})
              </span>
            } 
            key="pending"
          >
            <Table
              columns={outputValueColumns}
              dataSource={pendingData}
              rowKey="id"
              pagination={{ 
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) => 
                  `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`
              }}
              scroll={{ x: 3000 }}
              bordered
              size="small"
            />
          </TabPane>
          
          <TabPane 
            tab={
              <span>
                <CheckOutlined />
                已提交 ({submittedData.length})
              </span>
            } 
            key="submitted"
          >
            <Table
              columns={outputValueColumns}
              dataSource={submittedData}
              rowKey="id"
              pagination={{ 
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) => 
                  `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`
              }}
              scroll={{ x: 3000 }}
              bordered
              size="small"
            />
          </TabPane>
        </Tabs>
      </Card>

      {/* 编辑产值对话框 */}
      <Modal
        title="编辑产值记录"
        visible={editModalVisible}
        onOk={handleEditSubmit}
        onCancel={() => {
          setEditModalVisible(false);
          form.resetFields();
        }}
        width={800}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                label="序号"
                name="serialNumber"
                rules={[{ required: true, message: '请输入序号' }]}
              >
                <InputNumber style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="工号"
                name="employeeId"
                rules={[{ required: true, message: '请输入工号' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="姓名"
                name="employeeName"
                rules={[{ required: true, message: '请输入姓名' }]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                label="员工类型"
                name="employeeType"
                rules={[{ required: true, message: '请选择员工类型' }]}
              >
                <Select>
                  <Option value="公司自由人">公司自由人</Option>
                  <Option value="正式员工">正式员工</Option>
                  <Option value="外协人员">外协人员</Option>
                  <Option value="临时工">临时工</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="项目名称"
                name="projectName"
                rules={[{ required: true, message: '请输入项目名称' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="账期"
                name="accountPeriod"
                rules={[{ required: true, message: '请输入账期' }]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                label="项目编号"
                name="projectCode"
                rules={[{ required: true, message: '请输入项目编号' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="项目经理"
                name="projectManager"
                rules={[{ required: true, message: '请输入项目经理' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="部门"
                name="department"
                rules={[{ required: true, message: '请输入部门' }]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                label="项目地"
                name="projectLocation"
                rules={[{ required: true, message: '请输入项目地' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="入职时间"
                name="hireDate"
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="入项时间"
                name="projectStartDate"
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                label="离项时间"
                name="projectEndDate"
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="离职时间"
                name="resignationDate"
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="业务类型"
                name="businessType"
                rules={[{ required: true, message: '请选择业务类型' }]}
              >
                <Select>
                  <Option value="开发">开发</Option>
                  <Option value="设计">设计</Option>
                  <Option value="测试">测试</Option>
                  <Option value="运维">运维</Option>
                  <Option value="管理">管理</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                label="是否有订单"
                name="hasOrder"
                rules={[{ required: true, message: '请选择是否有订单' }]}
              >
                <Select>
                  <Option value="是">是</Option>
                  <Option value="否">否</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="单价（含税）"
                name="unitPrice"
                rules={[{ required: true, message: '请输入单价' }]}
              >
                <InputNumber 
                  style={{ width: '100%' }} 
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  parser={value => value.replace(/¥\s?|(,*)/g, '')}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="工作时长"
                name="workDuration"
                rules={[{ required: true, message: '请输入工作时长' }]}
              >
                <InputNumber style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                label="工作时长类型"
                name="workDurationType"
                rules={[{ required: true, message: '请选择工作时长类型' }]}
              >
                <Select>
                  <Option value="时">时</Option>
                  <Option value="天">天</Option>
                  <Option value="月">月</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="扣减"
                name="deduction"
                rules={[{ required: true, message: '请输入扣减' }]}
              >
                <InputNumber 
                  style={{ width: '100%' }} 
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  parser={value => value.replace(/¥\s?|(,*)/g, '')}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="当月产值"
                name="monthlyOutput"
                rules={[{ required: true, message: '请输入当月产值' }]}
              >
                <InputNumber 
                  style={{ width: '100%' }} 
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  parser={value => value.replace(/¥\s?|(,*)/g, '')}
                />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                label="当月产值（不含税）"
                name="monthlyOutputExcludingTax"
                rules={[{ required: true, message: '请输入当月产值（不含税）' }]}
              >
                <InputNumber 
                  style={{ width: '100%' }} 
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  parser={value => value.replace(/¥\s?|(,*)/g, '')}
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
};

export default OutputValueManagement;
